<?php
$tickers = $model->getAllCompany(); //Get a list of Company name to use for CGridView filter
$exchanges = $model->getAllExchanges();

if (!isset($afterUpdate)) {
    $afterUpdate = "function(id, data) {
        if($.cookie('isValidating') != 1) {
            $('#status').text('Done');
        }
    }";
}
if (!isset($datetimeFilter)) {
    $datetimeFilter = '';
}

foreach ($dataProvider->getData() as $row) {
    $row->timestamp = date("d/m/Y", strtotime($row->timestamp));
    $row->open = number_format($row->open, 2, '.', ',');
    $row->close = number_format($row->close, 2, '.', ',');
    $row->high = number_format($row->high, 2, '.', ',');
    $row->low = number_format($row->low, 2, '.', ',');
    $row->ref = number_format($row->ref, 2, '.', ',');
    $row->avg = number_format($row->avg, 2, '.', ',');
    $row->ceiling = number_format($row->ceiling, 2, '.', ',');
    $row->floor = number_format($row->floor, 2, '.', ',');
    $row->volumeKhopLenh = number_format($row->volumeKhopLenh, 2, '.', ',');
    $row->volumeAgreement = number_format($row->volumeAgreement, 2, '.', ',');
    $row->valueKhopLenh = number_format($row->valueKhopLenh, 2, '.', ',');
    $row->valueAgreement = number_format($row->valueAgreement, 2, '.', ',');
}


//Main gridview of the page
$gridCss = Yii::app()->baseUrl . '/css/stock/grid/fip-style.css'; //Update stock grid 's style/css here
$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'stock-grid',
    'rowCssClassExpression' => '$data->id . " ticker_" . $data->companyID .  " exchange_" . $data->exchangeID . " " . ($row%2?"even":"odd")', // add the companyID and ID to the <tr>'s class used for ajax
    'filter' => $filter,
    'dataProvider' => $dataProvider,
    'afterAjaxUpdate' => $afterUpdate,
    //css stuffs
    'cssFile' => $gridCss,
    'pager' => array('cssFile' => $gridCss),
    //column data
    'columns' => array(
        array(
            'name' => 'companyID',
            'value' => '$data->company->ticket', // in the companyID column, we get the ticker of the Company instead of the interger id
            'htmlOptions' => array('class' => 'ticket'), //this line only use for css
            'filter' => $tickers, //Instead of a input[type=text] filter, this line will make a dropdownlist filter for Tickers
        ),
        array(
            'name' => 'exchangeID',
            'value' => '$data->exchange->name', // in the companyID column, we get the ticker of the Company instead of the interger id
            'htmlOptions' => array('class' => 'exchanges'), //this line only use for css
            'filter' => $exchanges, //Instead of a input[type=text] filter, this line will make a dropdownlist filter for Tickers
        ),
        array(// display 'timestamp' at the 'dd/mm/yyyy' format
            'name' => 'timestamp',
            'value' => '$data->timestamp', //convert to 'dd/mm/yyyy' format
            'htmlOptions' => array('class' => 'timestamp'), //add class for this td, it's only for css
            'filter' => $datetimeFilter, //By default, we have a input[type=text] filter, now we will use the filter that the parent view specific
        ),
        array(
            'name' => 'open',
            'value' => '$data->open',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'close',
            'value' => '$data->close',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'high',
            'value' => '$data->high',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'low',
            'value' => '$data->low',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'ref',
            'value' => '$data->ref',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'avg',
            'value' => '$data->avg',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'ceiling',
            'value' => '$data->ceiling',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'floor',
            'value' => '$data->floor',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'volumeKhopLenh',
            'value' => '$data->volumeKhopLenh',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'volumeAgreement',
            'value' => '$data->volumeAgreement',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'valueKhopLenh',
            'value' => '$data->valueKhopLenh',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'name' => 'valueAgreement',
            'value' => '$data->valueAgreement',
            'htmlOptions' => array('class' => 'number'),
        ),
        array(
            'header' => 'Edit',
            'class' => 'CButtonColumn',
            'template' => '{update} {delete}', //update and delete buttons
            'buttons' => array(
                'update' => array(
                    'url' => " ",
                    'click' => 'showEditForm',
                    'imageUrl' => Yii::app()->request->baseUrl . '/images/stock-grid/set02/update.png',
                ),
                'delete' => array(
                    'imageUrl' => Yii::app()->request->baseUrl . '/images/stock-grid/set02/delete.png',
                ),
            ),
        ),
    ),
));
?>

<!--the add-button's used to show the add-form-->
<span id="add-stock" <?php if (isset($add) && $add == false)
    echo "style='display:none'"; ?>>+</span>

<!--Add-form will show up here, on this div -->
<div class="form" id="add-res">
    <?php
    $newmodel = new Stock;
    echo $this->renderPartial(
            '_addForm', array('model' => $newmodel)
    ); //Render the add-form right-here
    ?>
</div>
<!-- End of the `add-form` -->

<!--Column Filter Tips-->
<p id="col_filter_tips">
    <b>Tips</b>
    <br/>
    You may optionally enter a comparison operator (<b>&lt;</b>, <b>&lt;=</b>, <b>&gt;</b>, <b>&gt;=</b>, <b>&lt;&gt;</b>
    or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.
</p>
<script type="text/javascript">
    //Js function for UI (show/hide add button, add form...)
    $('#add-stock-form').hide(); //At the beginning, the addform is hidden

    $('#add-stock').live('click', function(){ //When someone clickes on the add-buton (id=#add-stock)
        $('#add-stock-form').toggle(); //The add-form will show up
        $('#add-stock').hide(); // and the add button'll temporarily hide
    });

    $('#btCancel').live('click', function(){ //If someone clickes on the cancel button
        $('#add-stock-form').toggle(); //Add-form will hide
        $('#add-stock').show(); //and button shows up again
    });
    //If they clickes on the Save button, the ajaxSubmitButton of Yii will work with the actionAdd and take care all of the task
    //addProcessor function will show the result for the customers
    //*********************************************************/

    //After added new row to the database, this function will show up the row to the top of the CGridview
    //just for people to review their results
    function addProcessor(result) {
        $('#add-stock-form input[type|="text"]').val(''); //reset the value they entered on the <input>
        $('table.items tbody').first().prepend(result); //Get the result row and prepend it on the top of the gridview
    }
    //*********************************************************/
    var backup = ''; //u'll see the explaination below
    function showEditForm() //This function's used to show up the update form when someone clicked on the update-button => update-button = $this
    {
        tr = $(this).parent().parent(); //At first, we get the <tr> element. The structure of the table is <tr>...<td><a class="update"></a></td>....</tr>
        //That's why we use the parent() twice to get the <tr>

        //In the code of the CGridView, we added the companyID in the <tr>'s class, now we'll get the companyID back
        //companyID of the row has the format '_####' (start with the _). Example this is the class string we got from the tr: '#### _123 odd'
        trclass = tr.attr('class'); //Now, get the class => we got '#### _123 odd'
        ticker = trclass.toString().substring(trclass.toString().indexOf('ticker_')); //then trim the string from the start to the fisrt 'ticker_' => we got 'ticker_123 odd'
        ticker = ticker.toString().substr(7, ticker.toString().indexOf(' ') - 7); //trim the string again from the 7 (ticker_ have 7 charactor) character to the first space.
        //Got it => it's '123' :D
        
        exchange = trclass.toString().substring(trclass.toString().indexOf('exchange_')); //then trim the string from the start to the fisrt 'ticker_' => we got 'ticker_123 odd'
        exchange = exchange.toString().substr(9, exchange.toString().indexOf(' ') - 9); //trim the string again from the 7 (ticker_ have 7 charactor) character to the first space.

        //in that part, the main idea is trying to replace a row full of '<td>text</td>' and replace id by '<input value=text />'. That's all!
        if($('#edit').length == 0) //Check if any row is editting, we only can edit one row at a time.
        {
            backup = tr.html(); //@ first, we backup the innerHTML of the tr to the backup variable.
            //then if someone don't want to update the row and they click 'Cancel', we can restore the tr to the normal state immediately

            td = tr.children('td'); //get all the td inside tr

            //the first column is Ticket, and we want it to appear as a list of ticket name
            tker = '<?php
    $x = CHtml::dropDownList('company', array(), $model->getAllCompany(), array('id' => 'col0', 'class' => 'editing'));
    $x = str_replace("\n", '', $x);
    echo $x;
    ?>'; //creating html code of Ticker list

                td.eq(0).html(tker); //replace the td's text by the ticker list
                $('#col0').val(parseInt(ticker)); //set selected for the current Ticket of the row

            exch = '<?php
    $x = CHtml::dropDownList('exchange', array(), $model->getAllExchanges(), array('id' => 'col1', 'class' => 'editing'));
    $x = str_replace("\n", '', $x);
    echo $x;
    ?>'; //creating html code of Ticker list

                td.eq(1).html(exch); //replace the td's text by the ticker list
                $('#col1').val(parseInt(exchange)); //set selected for the current Ticket of the row
                //for all the other td
                for(i = 2; i < 15; ++i) {
                    temp = td.eq(i).text(); //we get the text
                    input = '<input class="numericOnly" id="col' + i + '" class="editting" type="text" name="' + i + '" value="' + temp + '" />'; //then create the input with the value is the td's text
                    td.eq(i).html(input); //and push the input to the td :D
                }

                //The last td is a list of Edit+Cancel buttons, not content
                td.eq(15).html('<a id="editCancel"></a>&nbsp;<a id="editOK"></a>');

                tr.attr('id', 'edit'); // then we set the tr's id as 'edit'

                $('#col2').datepicker({ dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true, yearRange: '-20:+20' }); //make the datepicker work for the 2nd input (timestamp)
            }
        }
        //Now the edit form is working....
        //
        //
        //If they click CANCEL
        $('#editCancel').live('click', function() {
            tr = $(this).parent().parent(); //get the tr
            tr.html(backup); //restore the tr html to the previous state by 'backup' variable
            tr.attr('id', ''); //clear tr's id
        });

        //If they click OK
        $('#editOK').live('click', function() {
            //Just like the companyID, we also add the id of the row to tr's class
            //Pattern of the id '### _______' => The id is the first number of the class (###)
            id = $(this).parent().parent().attr('class');

            //now get the ID
            id = id.toString().substr(0, id.toString().indexOf(' '));

            //And send the ajaxRequest to the actionEdit
            $.ajax({
                type: 'POST',
                url: '<?php echo Yii::app()->createUrl('stock/edit'); ?>',
                //Getting all of the params
                data: 'id=' + id
                    + '&companyid=' + $('#col0 :selected').val()
                    + '&exchangeid=' + $('#col1 :selected').val()
                    + '&timestamp=' + $('#col2').val()
                    + '&open=' + $('#col3').val()
                    + '&close=' + $('#col4').val()
                    + '&high=' + $('#col5').val()
                    +'&low=' + $('#col6').val()
                    +'&ref=' + $('#col7').val()
                    +'&avg=' + $('#col8').val()
                    +'&ceiling=' + $('#col9').val()
                    +'&floor=' + $('#col10').val()
                    +'&volumeKhopLenh=' + $('#col11').val()
                    +'&volumeAgreement=' + $('#col12').val()
                    +'&valueKhopLenh=' + $('#col13').val()
                    +'&valueAgreement=' + $('#col14').val(),

                //This result is the number of rows were edited in the DB that's returned by actionEdit
                //We edit row by the ID (primarykey) that means only 1 row can be edited at a time
                //If result = 1, row was edited
                //if result = 0, that means something goes wrong or the customer just click OK without changing any attribute of the row
                success: function(result) {
                    //alert(result);
                    if(result == 0) {
                        $('#editCancel').trigger('click');
                        //nothing has been editted, so we restore the tr's innerHTML (the same job with click Cancel so we trigger the cancel button)
                    } else {
                        //if success, Cgridview now will automatic refresh => this' API of CGridView, i just use it
                        $.fn.yiiGridView.update('stock-grid', {
                            type:'POST',
                            url:'<?php echo Yii::app()->createUrl($this->route); ?>',
                            success:function() {
                                $.fn.yiiGridView.update('stock-grid');
                            },
                            failure:function() {
                                alert('We have some error. Please try again!'); //Alert if we have errors
                            }
                        });
                    }
                },
                error: function() {
                    alert('We have some error. Please try again!'); //Alert if we have errors
                }
            });
        });
        //These lines of code is used to prevent user to enter character instead of numbers into the numeric inputs
        $('.numericOnly').live('keypress', function(event) {
            var controlKeys = [8, 9, 13, 35, 36, 37, 39];
            var value = $(this).attr("value");
            // IE doesn't support indexOf
            var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
            // Some browsers just don't raise events for control keys. Easy.
            // e.g. Safari backspace.
            if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
            (48 <= event.which && event.which <= 57) || // Always 1 through 9
            (46 == event.which && value.toString().indexOf('.', 0) == -1) ||
                isControlKey) { // Opera assigns values for control keys.
                return;
            } else {
                event.preventDefault();
            }

        });
        //Sync width of add-line and cgridview
        function syncWidth() { //Definition of sync function
            var filter = $('.filters').eq(0).children('td'); //Cgridview has a filters on top with all input, all of these inputs are in the right position
            var inputs = $('.add-row').eq(1).children('td'); //So the add row of the page will have the same width of the filters' input
            var labels = $('.add-row').eq(0).children('td');
            for(i = 0; i < inputs.length; ++i) {
                inputs.eq(i).width(filter.eq(i).width());
                labels.eq(i).width(filter.eq(i).width());
            }
        }
        syncWidth(); //Call the function to sync the width
</script> <!--js script-->
